var saveButton = $('.save-button');

var EducationalDegreeModel = function(educationaldegrees) {

	var self = this;

	self.ids = []; 

	self.isValid = function() {
		var valid = true;
		var items = ko.toJS(self.educationalDegrees);
	
		if (items != undefined) {
			if (items.length != undefined) {
				for (i = 0; i < items.length; i++) {
					var item = items[i];
					valid = valid && ($.trim(item.EducationalDegree) != '');
					if (!valid) break;
				}		
			}
		}

		return valid;
	}

	self.educationalDegrees = ko.observableArray(ko.utils.arrayMap(educationaldegrees, function(educationaldegree) {
		self.ids.push(educationaldegree.Id);

		var viewModel = { 
							Id : educationaldegree.Id, 
							EducationalDegree : educationaldegree.EducationalDegree,
							RowState : 'unchanged'
						};

		viewModel.EducationalDegree = ko.observable(educationaldegree.EducationalDegree).extend( { modelUpdated : viewModel, validator: { 'saveButton': saveButton, saveButtonEnable: function() { return self.isValid(); } } } );
		
		return viewModel;
	}));

	self.deletedItems = [];

	self.acceptChanges = function(viewUpdates) {
		ko.utils.arrayForEach(self.educationalDegrees(), function(educationaldegree) {
			educationaldegree.RowState = 'unchanged';

			if (viewUpdates != null &&
				viewUpdates != undefined) {
				for (i = 0; i < viewUpdates.length; i++) {
					var viewUpdate = viewUpdates[i];
					if (educationaldegree.Id == viewUpdate.Id) {
						educationaldegree.Id = viewUpdate.GeneratedId;
						break;
					}
				}
			}
		});
	};


	self.add = function() {
		var id = 1;

		if (self.ids.length > 0) {
			var max = Math.max.apply(Math, self.ids);
			id = max + 1;
		}

		self.ids.push(id);

		var viewModel = {
							Id : id,
							EducationalDegree: '',
							RowState: 'added'
						};

		viewModel.EducationalDegree = ko.observable('').extend( { modelUpdated : viewModel, validator: { 'saveButton': saveButton, saveButtonEnable: function() { return self.isValid(); } } } );
		
		self.educationalDegrees.push(viewModel);

		setRemoveEducationalDegreeToolTips();

		var table = $('.educational-degrees-table');
		table.floatThead('reflow');

		if (!saveButton.hasClass('disabled')) saveButton.addClass('disabled');
		
		var rowInput = $('tr[data-id="' + id + '"] td .form-group input[placeholder="Educational degree..."]');
		rowInput.focus();
	};

	self.getChanges = function() {
		var updates = [];
		var items = ko.toJS(self.educationalDegrees);

		for (i = 0; i < items.length; i++) {
			var item = items[i];
			if (item.RowState != 'unchanged') updates.push( { Id: item.Id, EducationalDegree: item.EducationalDegree, RowState: item.RowState } );
		}

		for (i = 0; i < self.deletedItems.length; i++) {
			var item = self.deletedItems[i];
			updates.push( { Id: item.Id, EducationalDegree: '', RowState: 'deleted' } );	
		}

		return updates;
	}

	self.remove = function(educationaldegree) {
		unsetRemoveEducationalDegreeToolTips();
		
		if (educationaldegree.RowState != 'added') {
			educationaldegree.RowState = 'deleted';
			self.deletedItems.push(educationaldegree);
		}
		
		self.educationalDegrees.remove(educationaldegree);
		setRemoveEducationalDegreeToolTips();

		if (self.isValid())  saveButton.removeClass('disabled');
		else {
			if (!saveButton.hasClass('disabled')) saveButton.addClass('disabled');
		}
	};

	self.save = function() {
		if (saveButton.hasClass('disabled')) return;
		else saveButton.addClass('disabled');

		saveButton.button('loading');

		var updates = self.getChanges();
		var withUpdates = false;

		if (updates != null) withUpdates = (updates.length > 0);

		if (withUpdates) {
			$.ajax({
			    type: 'POST',
			    url: app.baseUrl() + 'index.php/references/update',
			    data: { 'data' : JSON.stringify(updates) },
			    dataType: 'json'
			}).done(function(response) {
				if (response != null) {
					if (response.saved) {
						var viewUpdates = null;

						if (response.viewUpdates != null &&
							response.viewUpdates != undefined) viewUpdates = response.viewUpdates;
						
						self.acceptChanges(viewUpdates);
						
						infoGritter({
							title: 'Record Update',
							text: 'Applied updates has been saved.'
						});
					}
					else {
						var message = 'Applied updates were not saved into the database.';

						if (response.message != undefined &&
							response.message != null) {
							if (response.message.trim() != '') message = response.message;
						}

						warningGritter({
							title: 'Record Update',
							text: message
						});						
					}
				}
			}).fail(function(response) {
				try {
					console.error(response);
				}
				catch (ex) {

				}

				errorGritter({
					title: 'Oooops',
					text: 'Something went wrong while applying the updates into the server.'
				});
			}).always(function() {
				saveButton.removeClass('disabled');
				saveButton.button('reset');
			});
		}
		else {
			saveButton.removeClass('disabled');
			saveButton.button('reset');
		}
	};

};

var setRemoveEducationalDegreeToolTips = function() {
	unsetRemoveEducationalDegreeToolTips();
	var removeLinks = $('a.remove-record');
	removeLinks.tooltip( { 
			'title' : 'Remove current line-item from the list.',
			'trigger' : 'hover',
			'container' : 'body' 
		} 
	);
};

var unsetRemoveEducationalDegreeToolTips = function() {
	var removeLinks = $('a.remove-record');
	removeLinks.tooltip('destroy');
};

$(document).ready(function() {
	var displaySection = $('.table-container');
	app.loader({ container: displaySection });

	$.post(app.baseUrl() + 'index.php/references/educationalDegrees').done(function(response) {
		var educationalDegrees = null;

		try {
			educationalDegrees = JSON.parse(response);
		}
		catch (ex) {

		}

		if (educationalDegrees != null) {
			ko.applyBindings(new EducationalDegreeModel(educationalDegrees));
			setRemoveEducationalDegreeToolTips();

			var table = $('.educational-degrees-table');
			table.floatThead({
			    scrollContainer: function(refTable){
					return refTable.closest('.table-container');
				}
			});
		}
	}).fail(function(response) {
		try {
			console.error(response);
		}
		catch (ex) {

		}

		errorGritter({
			title: 'Oooops',
			text: 'Something went wrong while loading the data to be displayed. Please try again.'
		});
	}).always(function() {
		app.loader('hide');
	});
});
